package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private SetmealService setmealService;

    @Override
    @Transactional
    public void addDandF(DishDto dishdto) {
        save(dishdto);
        List<DishFlavor> flavors = dishdto.getFlavors();
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishdto.getId());

        }
        dishFlavorService.saveBatch(flavors);
    }

    @Transactional
    @Override
    public void removeTwo(List<Long> ids) {
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Dish::getStatus, 1);
        lambdaQueryWrapper.in(Dish::getId, ids);
        int count = count(lambdaQueryWrapper);
        if (count > 0) {
            throw new CustomException("菜品在售状态不能直接删");
        }
        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.in(SetmealDish::getDishId, ids);
        int count1 = setmealDishService.count(setmealDishLambdaQueryWrapper);
        if (count1 > 0) {
            List<SetmealDish> list = setmealDishService.list(setmealDishLambdaQueryWrapper);
            for (SetmealDish setmealDish : list) {
                Long setmealId = setmealDish.getSetmealId();
                LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
                setmealLambdaQueryWrapper.eq(Setmeal::getId, setmealId);
                Setmeal one = setmealService.getOne(setmealLambdaQueryWrapper);
                if (one.getStatus() == 1) {
                    throw new CustomException("有包含此菜品套餐在售,不能直接删");
                }
            }
        }
        removeByIds(ids);
        setmealDishService.remove(setmealDishLambdaQueryWrapper);
    }
}
